package cn.anc.aonicardv.module.ui.recorder;

import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import java.io.File;

import butterknife.BindView;
import butterknife.OnClick;
import cn.anc.aonicardv.Configs;
import cn.anc.aonicardv.Constant;
import cn.anc.aonicardv.MyApplication;
import cn.anc.aonicardv.R;
import cn.anc.aonicardv.R2;
import cn.anc.aonicardv.bean.FirmwareBean;
import cn.anc.aonicardv.bean.ResponseResultBean;
import cn.anc.aonicardv.event.ScreenDisplayEvent;
import cn.anc.aonicardv.module.adpter.listener.OnCommonRecycleItemClickListener;
import cn.anc.aonicardv.module.adpter.recorder.RecorderSettingAdapter;
import cn.anc.aonicardv.module.ui.MainActivity;
import cn.anc.aonicardv.module.ui.base.BaseActivity;

import cn.anc.aonicardv.module.ui.my.AboutActivity;
import cn.anc.aonicardv.module.ui.my.HelpActivity;
import cn.anc.aonicardv.module.ui.my.SettingActivity;
import cn.anc.aonicardv.module.ui.my.SwitchAppLanuageActivity;
import cn.anc.aonicardv.util.ActivityUtils;
import cn.anc.aonicardv.util.DataClearManager;
import cn.anc.aonicardv.util.DateUtils;
import cn.anc.aonicardv.util.DialogUtils;
import cn.anc.aonicardv.util.LanguageConstants;
import cn.anc.aonicardv.util.SpUtils;
import cn.anc.aonicardv.util.StringUtils;
import cn.anc.aonicardv.util.UIUtil;
import cn.anc.aonicardv.util.ui.CarSettingGuiHandler;
import cn.anc.aonicardv.widget.CustomDialog;
import cn.anc.aonicardv.widget.FirmwareUpdateDialog;
import cn.anc.aonicardv.widget.WarningDialog;
import cn.anc.httpcontrolutil.CarControl;
import cn.anc.httpcontrolutil.CarControlCommand;
import cn.anc.httpcontrolutil.CarControlSettings;
import cn.anc.httpcontrolutil.SocketUtils;
import cn.anc.httpcontrolutil.cache.CacheManager;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by yangdai on 2017/6/19.
 */

public class RecorderSettingActivity extends BaseActivity implements OnCommonRecycleItemClickListener, CarControl.OnCarControlCallback, CarControl.OnHeartBeatCallBack, View.OnClickListener {

    @BindView(R2.id.tv_title)
    TextView titleTv;
    @BindView(R2.id.rv_recorder_setting)
    RecyclerView recorderSettingRv;

    @BindView(R2.id.rl_system_setting)
    LinearLayout systemSettingLl;
    @BindView(R2.id.rb_system_setting)
    RadioButton systemSettingRb;
    @BindView(R2.id.tv_system_setting)
    TextView systemSettingTv;

    @BindView(R2.id.rl_car_setting)
    LinearLayout carSettingLl;
    @BindView(R2.id.rb_car_setting)
    RadioButton carSetting;
    @BindView(R2.id.tv_car_setting)
    TextView carSettingTv;

    @BindView(R2.id.rl_wifi_setting)
    LinearLayout wifiSettingLl;
    @BindView(R2.id.rb_wifi_setting)
    RadioButton wifiSettingRb;
    @BindView(R2.id.tv_wifi_setting)
    TextView wifiSettingTv;

    @BindView(R2.id.rl_recorder_setting)
    LinearLayout recorderSettingLl;
    @BindView(R2.id.rb_recorder_setting)
    RadioButton recorderSettingRb;
    @BindView(R2.id.tv_recorder_setting)
    TextView recorderSettingTv;

    private RecorderSettingAdapter recorderSettingAdapter;
    private int position;
    public Dialog progressDialog;
    private WarningDialog warningDialog;
    private String model;
    private String buildTime;
    private boolean isAvailabilityUpdate;
    private FirmwareBean firmwareBean;
    private boolean isChecking = false;
    private boolean isFromUser;
    private DialogUtils dialogUtils;
    private ConnectivityManager connectivityManager;
    private Handler mHandler = new Handler();
    private String TAG = RecorderSettingActivity.class.getSimpleName();

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        setContentView(R.layout.activity_recorder_setting);
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
        connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        CarControl.doGetSdCardSpace(carControlCallback);
        initAPPSetting();
    }

    private void initAPPSetting() {
        if (CarControlSettings.getAllSettingItems().size() > 0) {
            CarControlSettings.SettingItem languageItem = CarControlSettings.getSettingItem(CarSettingGuiHandler.SETTING_ITEM_APP_LANGUAGE);
            if (null != languageItem){
                languageItem.settingItemValue = getLanguageText();
            }
            CarControlSettings.SettingItem cacheItem = CarControlSettings.getSettingItem(CarSettingGuiHandler.SETTING_ITEM_APP_CLEAR_CACHE);
            if (null != cacheItem){
                cacheItem.settingItemValue = getCacheText();
            }
        }
        recorderSettingAdapter.notifyDataSetChanged();
    }



    /**
     * 设置语言显示
     */
    private String getLanguageText() {
        String mLanguage = "";
        String selectedLanguage = SpUtils.getString(Constant.SpKeyParam.APP_LANUAGE, Configs.DEFUTL_LANGUAGE);
        if (selectedLanguage.equals(LanguageConstants.SIMPLIFIED_CHINESE)) {
            mLanguage= LanguageConstants.SIMPLIFIED_CHINESE_VALUE;
        } else if (selectedLanguage.equals(LanguageConstants.ENGLISH)) {
            mLanguage=LanguageConstants.ENGLISH_VALUE;
        } else if (selectedLanguage.equals(LanguageConstants.TRADITIONAL_CHINESE)) {
            mLanguage=LanguageConstants.TRADITIONAL_CHINESE_VALUE;
        }
        return mLanguage;
    }


    /**
     * 设置缓存显示
     */
    private String getCacheText() {
        String cacheStr = "";
        File file = new File(CacheManager.CACHE_ROOT_DIR);
        if (file.exists())
            try {
                cacheStr = DataClearManager.getCacheSize(file.getAbsoluteFile());
            } catch (Exception e) {
                e.printStackTrace();
            }
        cacheStr = TextUtils.isEmpty(cacheStr) ? "0.00MB" : cacheStr;
        return  cacheStr;
    }


    @Override
    public void initVariable() {
        recorderSettingAdapter = new RecorderSettingAdapter(this);
        dialogUtils = new DialogUtils();
        progressDialog = dialogUtils.getCustomProgressDialog(this);
        warningDialog = dialogUtils.getWarningDialog(this);
        model = CarControl.DeviceInfo.model;
        buildTime = CarControl.DeviceInfo.build_time;
        switchSystemSetting();
    }

    @Override
    public void setListener() {
        recorderSettingAdapter.setOnItemClickListener(this);
        warningDialog.okTv.setOnClickListener(this);
    }

    @Override
    public void initData() {
        recorderSettingRv.setLayoutManager(new LinearLayoutManager(this));
        recorderSettingRv.setAdapter(recorderSettingAdapter);
    }

    @Override
    public void onBackPressed() {
        exitSetting();
    }

    private void exitSetting() {
        progressDialog.show();
        CarControl.doStartRtsp(RecorderSettingActivity.this);
    }

    @OnClick(R2.id.tv_back)
    public void back() {
        if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.M && !CarControl.IsConnected.get()) {
            //停留0.5s钟等待  等待view加载完毕
            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    if (null != warningDialog)
                        warningDialog.setHint(getString(R.string.tip_cardv_disconnect)).show();
                }
            }, 500);
        } else
            exitSetting();
    }

    @OnClick(R2.id.rl_system_setting)
    public void switchSystemSetting() {
        titleTv.setText(getString(R.string.recoder_setting_system));
        if (SpUtils.getBoolean(Constant.SpKeyParam.IS_SETT_TIME_OF_MANUAL, false)) {
            CarControlSettings.SettingItem settingItem = CarControlSettings.getSettingItem(CarSettingGuiHandler.SETTING_ITEM_TIME);
            if (settingItem != null && null != settingItem.settingItemValue && CarSettingGuiHandler.SETTING_ITEM_TIME_OPTION_AUTO.equals(settingItem.settingItemValue)) {
                settingItem.settingItemValue = CarSettingGuiHandler.SETTING_ITEM_TIME_OPTION_MANUAL;
            }
        }

        recorderSettingAdapter.setData(CarControlSettings.getSettingItemGuiResourceListByType(CarSettingGuiHandler.CAR_SETTING_GROUP_ID.GROUP_SYSTEM_SETTING));
        resetCheckStatus();
        systemSettingLl.setBackground(UIUtil.getDrawable(R.color.recorder_setting_bg_color_s));
        systemSettingTv.setTextColor(UIUtil.getColor(R.color.recorder_edit_text_s));
        systemSettingRb.setChecked(true);
        switchWIFINetwork();
    }

    private void resetCheckStatus() {
        systemSettingRb.setChecked(false);
        systemSettingLl.setBackground(UIUtil.getDrawable(R.color.recorder_setting_bg_color));
        systemSettingTv.setTextColor(UIUtil.getColor(R.color.recorder_edit_text_n));
        carSetting.setChecked(false);
        carSettingLl.setBackground(UIUtil.getDrawable(R.color.recorder_setting_bg_color));
        carSettingTv.setTextColor(UIUtil.getColor(R.color.recorder_edit_text_n));
        wifiSettingRb.setChecked(false);
        wifiSettingLl.setBackground(UIUtil.getDrawable(R.color.recorder_setting_bg_color));
        wifiSettingTv.setTextColor(UIUtil.getColor(R.color.recorder_edit_text_n));
        recorderSettingRb.setChecked(false);
        recorderSettingLl.setBackground(UIUtil.getDrawable(R.color.recorder_setting_bg_color));
        recorderSettingTv.setTextColor(UIUtil.getColor(R.color.recorder_edit_text_n));
    }

    @OnClick(R2.id.rl_car_setting)
    public void switchCarSetting() {
        titleTv.setText(getString(R.string.my_setting));
        recorderSettingAdapter.setData(CarControlSettings.getSettingItemGuiResourceListByType(CarSettingGuiHandler.CAR_SETTING_GROUP_ID.GROUP_CAR_SAFE_SETTING));
        resetCheckStatus();
        carSetting.setChecked(true);
        carSettingLl.setBackground(UIUtil.getDrawable(R.color.recorder_setting_bg_color_s));
        carSettingTv.setTextColor(UIUtil.getColor(R.color.recorder_edit_text_s));
        switchWIFINetwork();
    }

    @OnClick(R2.id.rl_wifi_setting)
    public void switchWifiSetting() {
        titleTv.setText(getString(R.string.recoder_setting_wifi));
        recorderSettingAdapter.setData(CarControlSettings.getSettingItemGuiResourceListByType(CarSettingGuiHandler.CAR_SETTING_GROUP_ID.GROUP_WIFI_SETTING));
        resetCheckStatus();
        wifiSettingRb.setChecked(true);
        wifiSettingLl.setBackground(UIUtil.getDrawable(R.color.recorder_setting_bg_color_s));
        wifiSettingTv.setTextColor(UIUtil.getColor(R.color.recorder_edit_text_s));
        switchWIFINetwork();
    }

    private void switchWIFINetwork() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && SocketUtils.wifiNetwork != null) {
            ConnectivityManager.setProcessDefaultNetwork(SocketUtils.wifiNetwork);
        }
    }

    @OnClick(R2.id.rl_recorder_setting)
    public void switchRecorderMsg() {
        titleTv.setText(getString(R.string.recoder_setting_firmware));
        CarControl.doGetSdCardSpace(carControlCallback);
        recorderSettingAdapter.setData(CarControlSettings.getSettingItemGuiResourceListByType(CarSettingGuiHandler.CAR_SETTING_GROUP_ID.GROUP_RECORDER_MSG));
        resetCheckStatus();
        recorderSettingRb.setChecked(true);
        recorderSettingLl.setBackground(UIUtil.getDrawable(R.color.recorder_setting_bg_color_s));
        recorderSettingTv.setTextColor(UIUtil.getColor(R.color.recorder_edit_text_s));

    }

    @Override
    public void onResume() {
        super.onResume();
        recorderSettingAdapter.notifyItemChanged(position);
        CarControl.setOnHeartBeatCallBack(this);
        if (!CarControl.IsConnected.get()){
            if (null != warningDialog) {
                if (warningDialog.isShowing()) {
                    warningDialog.dismiss();
                }
                if (!warningDialog.isShowing() && !isDestroyed()) {
                    warningDialog.setHint(getString(R.string.tip_cardv_disconnect)).show();
                }

            }
        }

    }



    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(ScreenDisplayEvent event) {
        switchSystemSetting();
    }

    @Override
    public void OnItemClick(int position) {
        this.position = position;
        if (position >= recorderSettingAdapter.getSettingItemList().size())
            return;
        CarControlSettings.SettingItem settingItem = recorderSettingAdapter.getSettingItemList().get(position);

        if (null != settingItem.settingItemOptions && settingItem.settingItemOptions.size() == 2 && null != settingItem.settingItemValue && (CarSettingGuiHandler.SETTING_ITEM_OPTION_ON.equals(settingItem.settingItemValue) || CarSettingGuiHandler.SETTING_ITEM_OPTION_OFF.equals(settingItem.settingItemValue))) {

        } else if (CarSettingGuiHandler.SETTING_ITEM_FLICKER.equals(settingItem.settingItemKey)
                || CarSettingGuiHandler.SETTING_ITEM_LANGUAGE.equals(settingItem.settingItemKey)
                || CarSettingGuiHandler.SETTING_ITEM_AUTO_POWER_OFF.equals(settingItem.settingItemKey)
                || CarSettingGuiHandler.SETTING_ITEM_VOLUME.equals(settingItem.settingItemKey)
                || CarSettingGuiHandler.SETTING_ITEM_GSENSOR.equals(settingItem.settingItemKey)
                || CarSettingGuiHandler.SETTING_ITEM_TIRED_TIP.equals(settingItem.settingItemKey)
                || CarSettingGuiHandler.SETTING_ITEM_EV.equals(settingItem.settingItemKey)
                || CarSettingGuiHandler.SETTING_ITEM_TIME_FORMAT.equals(settingItem.settingItemKey)
                || CarSettingGuiHandler.SETTING_ITEM_STAMP.equals(settingItem.settingItemKey)
                || CarSettingGuiHandler.SETTING_ITEM_LCD_AUTO_OFF.equals(settingItem.settingItemKey)
                || CarSettingGuiHandler.SETTING_ITEM_IMAGE_QUALITY.equals(settingItem.settingItemKey)
                || CarSettingGuiHandler.SETTING_ITEM_RESOLUTION.equals(settingItem.settingItemKey)
                || CarSettingGuiHandler.SETTING_ITEM_SCREEN_DISPLAY.equals(settingItem.settingItemKey)
                || CarSettingGuiHandler.SETTING_ITEM_LOOP_RECORDING.equals(settingItem.settingItemKey)
                || CarSettingGuiHandler.SETTING_ITEM_TSR.equals(settingItem.settingItemKey)
                || CarSettingGuiHandler.SETTING_ITEM_WB.equals(settingItem.settingItemKey)
                || CarSettingGuiHandler.SETTING_ITEM_POWER_OFF_DELAY.equals(settingItem.settingItemKey)
                || CarSettingGuiHandler.SETTING_ITEM_RECORD_MODE.equals(settingItem.settingItemKey)
                || CarSettingGuiHandler.SETTING_ITEM_FORMAT_REMIND.equals(settingItem.settingItemKey)
                || CarSettingGuiHandler.SETTING_ITEM_SPEED_UNIT.equals(settingItem.settingItemKey)
                || CarSettingGuiHandler.SETTING_ITEM_GPS_FORMAT.equals(settingItem.settingItemKey)
                || CarSettingGuiHandler.SETTING_ITEM_OVERSPEED.equals(settingItem.settingItemKey)
                || CarSettingGuiHandler.SETTING_ITEM_PARKING_MODE.equals(settingItem.settingItemKey)
                || CarSettingGuiHandler.SETTING_ITEM_IR_LED.equals(settingItem.settingItemKey)
                || CarSettingGuiHandler.SETTING_ITEM_RTSP_SWITCH.equals(settingItem.settingItemKey)
        ) {
            if (CarSettingGuiHandler.SETTING_ITEM_EV.equals(settingItem.settingItemKey)) {
                ActivityUtils.jumpActivity(this, EVActivity.class, Constant.IntentKeyParam.SETTING_KEY, settingItem.settingItemKey);
            } else if (!CarSettingGuiHandler.SETTING_ITEM_STAMP.equals(settingItem.settingItemKey)) {
                ActivityUtils.jumpActivity(this, SettingSelectActivity.class, Constant.IntentKeyParam.SETTING_KEY, settingItem.settingItemKey);
            } else if (null!=CarControl.DeviceInfo.chip&&!CarControl.DeviceInfo.chip.equals("LT")) {
                ActivityUtils.jumpActivity(this, SettingSelectActivity.class, Constant.IntentKeyParam.SETTING_KEY, settingItem.settingItemKey, Constant.IntentKeyParam.SELECT_MODE, false);
            }

        } else if (CarSettingGuiHandler.SETTING_ITEM_TIME.equals(settingItem.settingItemKey)) {
            ActivityUtils.jumpActivity(this, TimeSettingActivity.class, Constant.IntentKeyParam.SETTING_KEY, settingItem.settingItemKey);
        } else if (CarSettingGuiHandler.SETTING_ITEM_DRIVER_ID.equals(settingItem.settingItemKey)) {
            ActivityUtils.jumpActivity(this, DriverNumberActivity.class, Constant.IntentKeyParam.SETTING_KEY, settingItem.settingItemKey);
        } else if (CarSettingGuiHandler.SETTING_ITEM_WIFI_PASSWORD_MODIFY.equals(settingItem.settingItemKey)) {
            ActivityUtils.jumpActivity(this, WifiSettingActivity.class);
        } else if (CarSettingGuiHandler.SETTING_ITEM_FORMAT_SD_CARD.equals(settingItem.settingItemKey)) {
            formatSdCardDialog();
        } else if (CarSettingGuiHandler.SETTING_ITEM_RESTORE_FACTORY_SETTINGS.equals(settingItem.settingItemKey)) {
            restoreFactorySettingsDialog();
        }  else if (CarSettingGuiHandler.SETTING_ITEM_APP_CLEAR_CACHE.equals(settingItem.settingItemKey)) {
            clearCache();
        } else if (CarSettingGuiHandler.SETTING_ITEM_APP_LANGUAGE.equals(settingItem.settingItemKey)) {
            ActivityUtils.jumpActivity(this, SwitchAppLanuageActivity.class);
        } else if (CarSettingGuiHandler.SETTING_ITEM_APP_HELP.equals(settingItem.settingItemKey)) {
            ActivityUtils.jumpActivity(this, HelpActivity.class);
        } else if (CarSettingGuiHandler.SETTING_ITEM_APP_ABOUT.equals(settingItem.settingItemKey)) {
            ActivityUtils.jumpActivity(this, AboutActivity.class);
        }

        else if (CarSettingGuiHandler.SETTING_ITEM_FIRMWARE_UPDATE.equals(settingItem.settingItemKey)) {
            isFromUser = true;
        }
    }

    private CustomDialog mClearialog;

    private void clearCache() {
        CarControlSettings.SettingItem cacheItem = CarControlSettings.getSettingItem(CarSettingGuiHandler.SETTING_ITEM_APP_CLEAR_CACHE);
        if (null == cacheItem ||StringUtils.isEmptyOrNull(cacheItem.settingItemValue)||cacheItem.settingItemValue.equals("0.00MB")){
            return;
        }

        if (mClearialog == null) {
            mClearialog = new CustomDialog.AlertBuilder(this)
                    .setContentText(getString(R.string.my_clear_cache_alert))
                    .setNegativeBtn(getString(R.string.ok), new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                            ProgressDialog progressDialog = dialogUtils.getProgressDialog(RecorderSettingActivity.this);
                            progressDialog.setMessage(getString(R.string.my_clearing_cache));
                            progressDialog.setCancelable(false);
                            progressDialog.show();
                            File file = new File(CacheManager.CACHE_ROOT_DIR);
                            if (file.exists())
                                DataClearManager.deleteFolderFile(file.getAbsolutePath(), true);
                            else
                                return;
                            Toast.makeText(RecorderSettingActivity.this, getString(R.string.my_clear_cache_hint), Toast.LENGTH_SHORT).show();
                            cacheItem.settingItemValue = "0.00MB";
                            progressDialog.dismiss();
                            recorderSettingAdapter.notifyDataSetChanged();
                        }
                    })
                    .setPositiveBtn(getString(R.string.cancel), new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    }).createPromptDialog();
            mClearialog.setCancelable(true);
            mClearialog.setCanceledOnTouchOutside(true);
        }
        mClearialog.show();


    }

    private CustomDialog formatSdCardDialog,restoreFactorySettingsDialog;

    public void restoreFactorySettingsDialog() {
        if (restoreFactorySettingsDialog == null) {
            restoreFactorySettingsDialog = new CustomDialog.AlertBuilder(this)
                    .setContentText(getString(R.string.my_restore_factory_settings_hint))
                    .setNegativeBtn(getString(R.string.ok), new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                            CarControl.doDefaultSetting(RecorderSettingActivity.this);
                            progressDialog.show();
                        }
                    })
                    .setPositiveBtn(getString(R.string.cancel), new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    }).createPromptDialog();
            restoreFactorySettingsDialog.setCancelable(true);
            restoreFactorySettingsDialog.setCanceledOnTouchOutside(true);
        }
        restoreFactorySettingsDialog.show();


    }




    public void formatSdCardDialog() {
        if (formatSdCardDialog == null) {
            formatSdCardDialog = new CustomDialog.AlertBuilder(this)
                    .setContentText(getString(R.string.my_format_sd_card_hint))
                    .setNegativeBtn(getString(R.string.ok), new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                            CarControl.doFormatTFCard(RecorderSettingActivity.this);
                            progressDialog.show();
                        }
                    })
                    .setPositiveBtn(getString(R.string.cancel), new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                          dialog.dismiss();
                        }
                    }).createPromptDialog();
            formatSdCardDialog.setCancelable(true);
            formatSdCardDialog.setCanceledOnTouchOutside(true);
        }
        formatSdCardDialog.show();


    }





    private FirmwareUpdateDialog firmwareUpdateDialog;
    private int mDialogId = 0;

    private void showUpdateDialog() {
        mDialogId++;
        firmwareUpdateDialog = new FirmwareUpdateDialog(RecorderSettingActivity.this, R.style.BaseDialogStyle, model, firmwareBean.getFirmware_name(), firmwareBean.getFirmware_md5(), mDialogId);
        firmwareUpdateDialog.show();
        firmwareUpdateDialog.setUpdateContent(firmwareBean.getUpgrade_log());
        firmwareUpdateDialog.setVersionCode(firmwareBean.getVersion());
    }

    private CarControlCallback carControlCallback = new CarControlCallback();

    class CarControlCallback implements CarControl.OnCarControlCallback {
        @Override
        public void OnCommandCallback(int code, CarControl.CommandResponseInfo info) {
            if (code < 0 || isDestroyed())
                return;
            switch (info.msg_id) {
                case CarControlCommand.CAR_CONTROL_COMMAND_GET_CARD_SPACE:
                    if (CarControlSettings.getAllSettingItems().size() > 0) {
                        CarControlSettings.SettingItem settingItem = CarControlSettings.getSettingItem(CarSettingGuiHandler.SETTING_ITEM_SD_CARD_SIZE);
                        if (null != settingItem)
                            settingItem.settingItemValue = info.param;
                    }
                    recorderSettingAdapter.notifyDataSetChanged();
                    break;

                case CarControlCommand.CAR_CONTROL_COMMAND_ID_STOP_RTSP:
                    break;
                default:
                    break;
            }
        }
    }

    @Override
    public void OnCommandCallback(int code, CarControl.CommandResponseInfo info) {
        if (code < 0) {
            progressDialog.dismiss();
            return;
        }
        switch (info.msg_id) {
            case CarControlCommand.CAR_CONTROL_COMMAND_ID_FORMAT:
                if (null!=progressDialog){
                    progressDialog.dismiss();
                }

                if (info.rval < 0) {
                    if (info.rval == -31) {
                        Toast.makeText(RecorderSettingActivity.this, getString(R.string.recorder_no_sd_card), Toast.LENGTH_SHORT).show();
                    } else if (info.rval == -32) {
                        Toast.makeText(RecorderSettingActivity.this, getString(R.string.recorder_format_error_sd_card), Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(RecorderSettingActivity.this, getString(R.string.take_photo_fail), Toast.LENGTH_SHORT).show();
                    }
                    break;
                }
                if (info.rval == 0) {
                    CarControl.doGetSdCardSpace(carControlCallback);
                    Toast.makeText(this, getString(R.string.my_format_sd_card_hint2), Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(this, getString(R.string.my_format_sd_card_hint3), Toast.LENGTH_SHORT).show();
                }

                break;
            case CarControlCommand.CAR_CONTROL_COMMAND_ID_DEFAULT_SETTING:
                if (null!=progressDialog){
                    progressDialog.dismiss();
                }

                CarControl.HeartBeatStop();
                Toast.makeText(this, getString(R.string.my_restore_factory_settings_hint2), Toast.LENGTH_SHORT).show();
                break;
            case CarControlCommand.CAR_CONTROL_COMMAND_ID_START_RTSP:
                if (null!=progressDialog){
                    progressDialog.dismiss();
                }

                finish();
                break;
            default:
                if (null!=progressDialog){
                    progressDialog.dismiss();
                }
                break;

        }
    }

    @Override
    public void OnHeartBeatConnectOK() {
        Log.e("llcDebug", "-------------心跳成功-----:OnHeartBeatConnectOK");
    }

    @Override
    public void OnHeartBeatConnectFail() {
        Log.e("llcDebug", "-------------心跳失败-----:OnHeartBeatConnectFail");
    }

    @Override
    public void OnHeartBeatDisconnect() {
        Log.e("llcDebug", "-------------心跳断开-----:OnHeartBeatDisconnect");
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M || !recorderSettingRb.isChecked()) {
            if (null != firmwareUpdateDialog && firmwareUpdateDialog.isShowing()) {
                firmwareUpdateDialog.dismiss();
            }
            //停留0.5s钟等待  等待view加载完毕
            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    if (null != warningDialog)
                        warningDialog.setHint(getString(R.string.tip_cardv_disconnect)).show();
                }
            }, 500);

        }
    }

    @Override
    public void onClick(View v) {
        warningDialog.dismiss();
        startActivity(new Intent(this, MainActivity.class));
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        switchWIFINetwork();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && Build.VERSION.SDK_INT <= Build.VERSION_CODES.M && !CarControl.IsConnected.get()) {
            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    if (null != warningDialog)
                        warningDialog.setHint(getString(R.string.tip_cardv_disconnect)).show();
                }
            }, 500);

            return true;
        }else if (keyCode == KeyEvent.KEYCODE_BACK ){
            exitSetting();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }


}
